package com.shicheng.mediaplayer.media;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.shicheng.mediaplayer.R;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

import static android.content.Context.AUDIO_SERVICE;

/**
 * Created by SHICHENG
 * <p>
 * Time on 2021/11/08
 */
public class MediaManager {

    private static MediaManagerBuilder mediaManagerBuilder;

    public static MediaManagerBuilder builder() {
        mediaManagerBuilder = new MediaManagerBuilder();

        return mediaManagerBuilder;
    }

    public static MediaPlayer getMediaPlayer(){
        if (mediaManagerBuilder!=null){
            return mediaManagerBuilder.mediaPlayer;
        }
        return null;
    }


    public static void start() {
        mediaManagerBuilder.start();
    }

    public static void release() {
        mediaManagerBuilder.release();
    }
    public static boolean isPlaying() {
        if (mediaManagerBuilder != null) {
            return mediaManagerBuilder.isPlaying();
        }
        return false;
    }

    public static void stop() {
        if (mediaManagerBuilder != null && mediaManagerBuilder.isPlaying()) {
            mediaManagerBuilder.stop();
        }
    }

    public static void pause() {
        if (mediaManagerBuilder != null) {
            mediaManagerBuilder.pause();
        }
    }

    public static void resume() {
        if (mediaManagerBuilder != null) {
            mediaManagerBuilder.resume();
        }
    }

    public static void removeAll() {
        if (mediaManagerBuilder != null) {
            mediaManagerBuilder.removeAll();
        }
    }

    public static class MediaManagerBuilder {

        public final String TAG = this.getClass().getSimpleName();
        private Handler handler = new Handler();
        private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。

        private Context context;
        private MediaConfig config;
        private MediaCallBack mediaListener;
        private MediaPlayer mediaPlayer;
        private boolean DEBUG = false;
        private SimpleDateFormat format;
        private Timer timer;
        private SeekBar seekBar;
        private AudioManager audioManager;
        private Toast toast;
        private boolean openToast = false;

        private MediaManagerBuilder() {
            this.config = new MediaConfig();
            this.mediaPlayer = new MediaPlayer();
            this.format = new SimpleDateFormat("mm:ss");
        }

        /**
         * 当前Activity的上下文
         *
         * @param context
         * @return
         */

        public MediaManagerBuilder setContext(Context context) {
            this.context = context;
            audioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);
            return this;
        }

        /**
         *
         */
        public MediaManagerBuilder setOpenToast(boolean b) {
            this.openToast = b;
            return this;
        }


        /**
         * 设置MediaPlayer Url链接
         *
         * @param url
         * @return
         */
        public MediaManagerBuilder setUrl(String url) {
            this.config.url = url;
            return this;
        }

        /**
         * 设置播放进度监听回调
         *
         * @param mediaListener
         * @return
         */
        public MediaManagerBuilder setMediaListener(MediaCallBack mediaListener) {
            this.mediaListener = mediaListener;
            return this;
        }

        /**
         * 设置是否是debug
         *
         * @param b
         * @return
         */
        public MediaManagerBuilder setDebugModel(boolean b) {
            this.DEBUG = b;
            return this;
        }

        /**
         * 设置进度条
         */
        public MediaManagerBuilder setProgressSeek(SeekBar seek) {
            this.seekBar = seek;
            return this;
        }

        public MediaManagerBuilder setAudioManager(AudioManager audioManager){
            this.audioManager = audioManager;
            return this;
        }



        /**
         * 初始化MediaPlayer
         */

        public MediaManagerBuilder build() {
            if (openToast){
                initToast();
            }
            Uri uri = Uri.parse(config.url);
            //播放器不能为空
            if (mediaPlayer != null) {
                //如果是正在播放的状态 需要暂停上一个
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaListener.stop();
                }
            }
            //重置播放器
            mediaPlayer.release();
            //创建新的播放器
            mediaPlayer = new MediaPlayer();
            if (seekBar != null) {
                seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                        isSeekBarChanging = true;
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        isSeekBarChanging = false;
                        mediaPlayer.seekTo(seekBar.getProgress());
                    }
                });
            }
            try {
                mediaPlayer.setDataSource(config.url); //指定音频文件的路径
                mediaPlayer.prepareAsync();//让mediaplayer进入准备状态
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        if (seekBar != null) {
                            seekBar.setMax(mediaPlayer.getDuration());
                        }
                        mediaListener.prepare(mediaPlayer.getDuration(), format.format(mediaPlayer.getDuration()) + "");
                    }
                });
                mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaListener.error();
                        return false;
                    }
                });
                // 监听音频播放完的代码，实现音频的自动循环播放
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer arg0) {
                        if (seekBar!=null){
                            timer.cancel();
                        }
                        mediaListener.completion();
                    }
                });
            } catch (IOException e) {
                if (mediaPlayer!=null){
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
                mediaListener.error();
                e.printStackTrace();
            }
            return this;
        }


        /**
         * 开始播放
         */
        private void start() {
            //开始播放
            if (mediaPlayer!=null){
                mediaPlayer.start();
                mediaListener.start();
                if (seekBar != null) {
                    mediaPlayer.seekTo(seekBar.getProgress());
                    //监听播放时回调函数
                    timer = new Timer();
                    timer.schedule(new TimerTask() {

                        Runnable updateUI = new Runnable() {
                            @Override
                            public void run() {
                                if (mediaPlayer != null && mediaPlayer.getCurrentPosition() != -1) {
                                    mediaListener.progress(mediaPlayer.getCurrentPosition(), mediaPlayer.getDuration());
                                }
                            }
                        };

                        @Override
                        public void run() {
                            if (!isSeekBarChanging) {
                                if (seekBar != null) {
                                    seekBar.setProgress(mediaPlayer.getCurrentPosition());
                                }
                                handler.post(updateUI);
                            }

                        }
                    }, 0, 50);
                }
                if (DEBUG) {
                    Log.i(TAG, "start: media start");
                }
                if (openToast){
                    getCurrentVolume();
                }
            }
        }

        /**
         * 停止播放
         */
        private void stop() {
           try {
               //播放器不能为空  为空终止
               if (mediaPlayer == null) {
                   return;
               }
               if (mediaPlayer.isPlaying()){
                   mediaPlayer.stop();
                   mediaListener.stop();
               }
               if (DEBUG) {
                   Log.i(TAG, "start: media stop");
               }
           }catch (Throwable t){

           }
        }

        /**
         * 暂停播放
         */
        private void pause() {
            //播放器不能为空  为空终止
            if (mediaPlayer == null) {
                return;
            }
            mediaPlayer.pause();
            mediaListener.stop();
            if (DEBUG) {
                Log.i(TAG, "start: media pause");
            }
        }

        /**
         * 继续播放
         */
        private void resume() {
            //播放器不能为空  为空终止
            if (mediaPlayer == null) {
                return;
            }
            mediaPlayer.start();
            mediaListener.start();
            if (DEBUG) {
                Log.i(TAG, "start: media resume");
            }
            if (openToast){
                getCurrentVolume();
            }
        }

        /**
         * 是否是播放中
         */
        private boolean isPlaying() {
            if (mediaPlayer != null) {
                try {
                    if (mediaPlayer.isPlaying()){
                        return true;
                    }else{
                        return false;
                    }
                }catch (Throwable t){

                }
            }
            return false;
        }
        /**
         * 是否是播放中
         */
        private void release() {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer.reset();
                mediaPlayer = null;
            }
        }
        /**
         * 移除所有 清除内存
         */
        public void removeAll() {
            isSeekBarChanging = true;
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            if (mediaPlayer != null) {
                try {
                    if (mediaPlayer.isPlaying()){
                        mediaPlayer.stop();
                    }
                }catch (Throwable t){

                }
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }

        /**
         * 初始化Toast
         */
        private void initToast() {
            LayoutInflater inflater = LayoutInflater.from(context);
            View view = inflater.inflate(R.layout.volume_too_low, null);
            if (toast != null) {
                toast.cancel();
            }
            toast = new Toast(context);
            toast.setGravity(Gravity.CENTER,0,0);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(view);
        }

        private void getCurrentVolume() {
            //        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);// 0
//        int current = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
//        Log.e("service", "通话音量值：" + max + "-" + current);

//        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);// 1
//        int current = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
//        Log.e("service", "系统音量值：" + max + "-" + current);

//        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);// 2
//        int  current = audioManager.getStreamVolume(AudioManager.STREAM_RING);
//        Log.e("service", "系统铃声值：" + max + "-" + current);

//            int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);// 3
            int current = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

            if (current == 0){
                if (toast!=null){
                    toast.show();
                }
            }

//        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);// 4
//        int current = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
//        Log.e("service", "闹铃音量值：" + max + "-" + current);

//        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);// 5
//        int current = audioManager
//                .getStreamVolume(AudioManager.STREAM_NOTIFICATION);
//        Log.e("service", "提示声音音量值：" + max + "-" + current);
        }

    }


}
